import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

/**
 * 应用入口文件
 * @description 应用的启动入口，负责初始化React应用和全局配置
 */

/**
 * 开发环境配置
 */
if (import.meta.env.DEV) {
  // 开发环境下启用React严格模式
  console.log('🚀 课程表管理系统启动中...');
  console.log('📦 环境信息:', {
    mode: import.meta.env.MODE,
    dev: import.meta.env.DEV,
    prod: import.meta.env.PROD,
    baseUrl: import.meta.env.BASE_URL
  });
}

/**
 * 全局错误处理
 */
const handleGlobalError = (error: ErrorEvent) => {
  console.error('全局错误捕获:', {
    message: error.message,
    filename: error.filename,
    lineno: error.lineno,
    colno: error.colno,
    error: error.error
  });
  
  // 在生产环境中可以上报错误到监控系统
  if (import.meta.env.PROD) {
    // 错误上报逻辑
    // reportError(error);
  }
};

/**
 * 未处理的Promise拒绝处理
 */
const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
  console.error('未处理的Promise拒绝:', event.reason);
  
  // 防止默认的错误处理
  event.preventDefault();
  
  // 在生产环境中可以上报错误到监控系统
  if (import.meta.env.PROD) {
    // 错误上报逻辑
    // reportError(new Error(event.reason));
  }
};

/**
 * 性能监控
 */
const initPerformanceMonitoring = () => {
  if ('performance' in window && 'PerformanceObserver' in window) {
    // 监控页面加载性能
    const observer = new PerformanceObserver((list) => {
      const entries = list.getEntries();
      entries.forEach((entry) => {
        if (entry.entryType === 'navigation') {
          const navigationEntry = entry as PerformanceNavigationTiming;
          console.log('📊 页面加载性能:', {
            domContentLoaded: navigationEntry.domContentLoadedEventEnd - navigationEntry.domContentLoadedEventStart,
            loadComplete: navigationEntry.loadEventEnd - navigationEntry.loadEventStart,
            totalTime: navigationEntry.loadEventEnd - navigationEntry.fetchStart
          });
        }
      });
    });
    
    observer.observe({ entryTypes: ['navigation'] });
  }
};

/**
 * 浏览器兼容性检查
 */
const checkBrowserCompatibility = () => {
  const requiredFeatures = [
    'Promise',
    'fetch',
    'localStorage',
    'sessionStorage',
    'JSON'
  ];
  
  const missingFeatures = requiredFeatures.filter(feature => !(feature in window));
  
  if (missingFeatures.length > 0) {
    console.warn('⚠️ 浏览器兼容性警告，缺少以下特性:', missingFeatures);
    
    // 可以显示兼容性提示
    const compatibilityWarning = document.createElement('div');
    compatibilityWarning.innerHTML = `
      <div style="
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        background: #ff4d4f;
        color: white;
        padding: 12px;
        text-align: center;
        z-index: 9999;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      ">
        ⚠️ 您的浏览器版本过低，可能影响应用正常使用。建议升级到最新版本的Chrome、Firefox或Safari。
      </div>
    `;
    document.body.appendChild(compatibilityWarning);
  }
};

/**
 * 应用初始化配置
 */
const initializeApp = async () => {
  try {
    // 检查浏览器兼容性
    checkBrowserCompatibility();
    
    // 初始化性能监控
    if (import.meta.env.DEV) {
      initPerformanceMonitoring();
    }
    
    // 添加全局错误监听器
    window.addEventListener('error', handleGlobalError);
    window.addEventListener('unhandledrejection', handleUnhandledRejection);
    
    // 设置页面基本信息
    document.title = '课程表管理系统';
    
    // 设置favicon（如果存在）
    const favicon = document.querySelector('link[rel="icon"]') as HTMLLinkElement;
    if (!favicon) {
      const newFavicon = document.createElement('link');
      newFavicon.rel = 'icon';
      newFavicon.type = 'image/x-icon';
      newFavicon.href = '/favicon.ico';
      document.head.appendChild(newFavicon);
    }
    
    // 设置viewport meta标签
    let viewport = document.querySelector('meta[name="viewport"]') as HTMLMetaElement;
    if (!viewport) {
      viewport = document.createElement('meta');
      viewport.name = 'viewport';
      document.head.appendChild(viewport);
    }
    viewport.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';
    
    // 设置字符编码
    let charset = document.querySelector('meta[charset]') as HTMLMetaElement;
    if (!charset) {
      charset = document.createElement('meta');
      charset.setAttribute('charset', 'UTF-8');
      document.head.insertBefore(charset, document.head.firstChild);
    }
    
    // 设置应用描述
    let description = document.querySelector('meta[name="description"]') as HTMLMetaElement;
    if (!description) {
      description = document.createElement('meta');
      description.name = 'description';
      document.head.appendChild(description);
    }
    description.content = '课程表管理系统 - 支持学生管理、课程管理、课表安排和多课表混合显示的前端应用';
    
    // 设置关键词
    let keywords = document.querySelector('meta[name="keywords"]') as HTMLMetaElement;
    if (!keywords) {
      keywords = document.createElement('meta');
      keywords.name = 'keywords';
      document.head.appendChild(keywords);
    }
    keywords.content = '课程表,学生管理,课程管理,教育管理,课程安排,React,TypeScript';
    
    // 设置作者信息
    let author = document.querySelector('meta[name="author"]') as HTMLMetaElement;
    if (!author) {
      author = document.createElement('meta');
      author.name = 'author';
      document.head.appendChild(author);
    }
    author.content = 'Course Schedule System Team';
    
    // 设置主题色
    let themeColor = document.querySelector('meta[name="theme-color"]') as HTMLMetaElement;
    if (!themeColor) {
      themeColor = document.createElement('meta');
      themeColor.name = 'theme-color';
      document.head.appendChild(themeColor);
    }
    themeColor.content = '#1890ff';
    
    // 设置PWA相关meta标签
    let appleMobileWebAppCapable = document.querySelector('meta[name="apple-mobile-web-app-capable"]') as HTMLMetaElement;
    if (!appleMobileWebAppCapable) {
      appleMobileWebAppCapable = document.createElement('meta');
      appleMobileWebAppCapable.name = 'apple-mobile-web-app-capable';
      appleMobileWebAppCapable.content = 'yes';
      document.head.appendChild(appleMobileWebAppCapable);
    }
    
    let appleMobileWebAppStatusBarStyle = document.querySelector('meta[name="apple-mobile-web-app-status-bar-style"]') as HTMLMetaElement;
    if (!appleMobileWebAppStatusBarStyle) {
      appleMobileWebAppStatusBarStyle = document.createElement('meta');
      appleMobileWebAppStatusBarStyle.name = 'apple-mobile-web-app-status-bar-style';
      appleMobileWebAppStatusBarStyle.content = 'default';
      document.head.appendChild(appleMobileWebAppStatusBarStyle);
    }
    
    // 预加载关键资源
    const preloadLinks = [
      { href: '/fonts/chinese.woff2', as: 'font', type: 'font/woff2', crossorigin: 'anonymous' }
    ];
    
    preloadLinks.forEach(({ href, as, type, crossorigin }) => {
      const existingLink = document.querySelector(`link[href="${href}"]`);
      if (!existingLink) {
        const link = document.createElement('link');
        link.rel = 'preload';
        link.href = href;
        link.as = as;
        if (type) link.type = type;
        if (crossorigin) link.crossOrigin = crossorigin;
        document.head.appendChild(link);
      }
    });
    
    console.log('✅ 应用初始化完成');
    
  } catch (error) {
    console.error('❌ 应用初始化失败:', error);
    
    // 显示初始化失败提示
    const errorDiv = document.createElement('div');
    errorDiv.innerHTML = `
      <div style="
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100vh;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        text-align: center;
        padding: 20px;
      ">
        <h1 style="color: #ff4d4f; margin-bottom: 16px;">应用初始化失败</h1>
        <p style="color: #666; margin-bottom: 24px;">抱歉，应用启动时发生了错误</p>
        <button onclick="window.location.reload()" style="
          padding: 8px 16px;
          background: #1890ff;
          color: white;
          border: none;
          border-radius: 4px;
          cursor: pointer;
        ">重新加载</button>
      </div>
    `;
    document.body.appendChild(errorDiv);
    throw error;
  }
};

/**
 * 启动应用
 */
const startApp = async () => {
  try {
    // 初始化应用配置
    await initializeApp();
    
    // 获取根元素
    const rootElement = document.getElementById('root');
    if (!rootElement) {
      throw new Error('找不到根元素 #root');
    }
    
    // 创建React根实例
    const root = ReactDOM.createRoot(rootElement);
    
    // 渲染应用
    root.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>
    );
    
    // 开发环境下的额外配置
    if (import.meta.env.DEV) {
      // 启用React DevTools
      if (typeof window !== 'undefined') {
        const devtools = (window as any).__REACT_DEVTOOLS_GLOBAL_HOOK__;
        if (devtools && devtools.onCommitFiberRoot) {
          devtools.onCommitFiberRoot = (id: any, root: any) => {
            // React DevTools集成
          };
        }
      }
      
      console.log('🎉 课程表管理系统启动成功！');
      console.log('🔧 开发模式已启用');
    }
    
  } catch (error) {
    console.error('❌ 应用启动失败:', error);
    
    // 显示启动失败页面
    const errorHTML = `
      <div style="
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100vh;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        text-align: center;
        padding: 20px;
        background-color: #f5f5f5;
      ">
        <div style="
          background: white;
          padding: 40px;
          border-radius: 8px;
          box-shadow: 0 2px 8px rgba(0,0,0,0.1);
          max-width: 400px;
        ">
          <h1 style="color: #ff4d4f; margin-bottom: 16px; font-size: 24px;">启动失败</h1>
          <p style="color: #666; margin-bottom: 24px; line-height: 1.5;">
            课程表管理系统启动时发生了错误，请尝试刷新页面或检查浏览器控制台获取更多信息。
          </p>
          <div style="display: flex; gap: 12px; justify-content: center;">
            <button onclick="window.location.reload()" style="
              padding: 10px 20px;
              background: #1890ff;
              color: white;
              border: none;
              border-radius: 4px;
              cursor: pointer;
              font-size: 14px;
            ">重新加载</button>
            <button onclick="console.log('错误详情:', '${error}')" style="
              padding: 10px 20px;
              background: #f5f5f5;
              color: #666;
              border: 1px solid #d9d9d9;
              border-radius: 4px;
              cursor: pointer;
              font-size: 14px;
            ">查看详情</button>
          </div>
        </div>
      </div>
    `;
    
    document.body.innerHTML = errorHTML;
  }
};

// 启动应用
startApp();

// 热模块替换支持（开发环境）
if (import.meta.hot) {
  import.meta.hot.accept('./App', () => {
    console.log('🔄 热更新: App组件已更新');
  });
}